package com.example.winleung.sos;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
      private TextView textView;
      private ImageView imgDog;
      private Button btnNext;
      private int[] dogimgs={R.drawable.dog1,R.drawable.dog2,R.drawable.dog3,R.drawable.dog4,R.drawable.dog5};
      private int index=0;
    private Handler handler;
    private final int MSG_CHANGE_WANZI = 1001;

    //是否处于暂停状态
    private boolean isPause = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgDog=findViewById(R.id.imgDog);
        btnNext = findViewById(R.id.btnNext);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what ==MSG_CHANGE_WANZI){
                    index=(index+1)%dogimgs.length;
                    imgDog.setImageResource(dogimgs[index]);
                    return true;
                }
                return false;
            }
        });



        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPause=!isPause;
                //自动换图片
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true){
                            try{
                                Thread.sleep(2000);
                            }catch (InterruptedException e){
                                e.printStackTrace();
                            }
                            //在子线程中不可以修改主线程创建的view
                            //需要实用消息机制 告诉主线程更新
                            if(!isPause) {
                                Message message = new Message();
                                message.what = MSG_CHANGE_WANZI;
                                handler.sendMessage(message);
                                Log.e("MainActity", "send change message");
                            }

                        }
                    }
                }).start();

            }

        });
    }


}
